package com.adlx.dingdong.mall.config;

import com.adlx.dingdong.mall.user.api.UserFeignClient;
import com.adlx.dingdong.mall.user.dto.UserDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.encoding.Md5PasswordEncoder;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.util.StringUtils;

import java.util.Collections;

public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserFeignClient userService;

    private String defaultSecret;
    private String defaultPassword;
    private Md5PasswordEncoder encoder = new Md5PasswordEncoder();


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UserDTO user = userService.getUserByUsername(username);
        if (user == null) {
            throw new UsernameNotFoundException(String.format("User doesn't exist: username=%s", username));
        }
        return new org.springframework.security.core.userdetails.User(username, user.getPassword(), Collections.singletonList(new SimpleGrantedAuthority("ROLE_USER")));
    }

    public String getDefaultPassword() {
        return defaultPassword;
    }

    public void setDefaultPassword(String defaultPassword) {
        this.defaultPassword = StringUtils.hasText(defaultPassword) ? defaultPassword : "123456";
        setDefaultSecret(encoder.encodePassword(this.defaultPassword, null));
    }

    public String getDefaultSecret() {
        if (defaultSecret == null) {
            setDefaultPassword(null);
        }
        return defaultSecret;
    }

    public void setDefaultSecret(String defaultSecret) {
        this.defaultSecret = defaultSecret;
    }

}
